package com.jinly.ryder.ssh.service.impl;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jinly.ryder.common.error.SystemErrorType;
import com.jinly.ryder.common.service.SystemSettingService;
import com.jinly.ryder.common.service.model.setting.SshSetting;
import com.jinly.ryder.common.utils.SshKeyUtil;
import com.jinly.ryder.ssh.command.OsCommand;
import com.jinly.ryder.ssh.command.SshCopyIdCommand;
import com.jinly.ryder.ssh.command.model.OsInfo;
import com.jinly.ryder.ssh.service.SshConnectService;
import com.jinly.ryder.ssh.service.model.SshConnect;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

@Slf4j
@Service
@RequiredArgsConstructor
public class SshConnectServiceImpl implements SshConnectService {

    private final SystemSettingService systemSettingService;

    public Session getSshSession(SshConnect sshConnect) {
        if (ObjectUtils.isEmpty(sshConnect.getUsername())) {
            sshConnect.setUsername("root");
        }
        if (sshConnect.getPort() == null) {
            sshConnect.setPort(22);
        }
        Session sshSession = null;
        SshSetting sshSetting = systemSettingService.getSettingItem(SshSetting.class);
        try {
            JSch jsch = new JSch();
            if (sshConnect.getType() == 1) {
                String priKey = SshKeyUtil.getPriKeyFileName(sshSetting.getPriKey());
                jsch.addIdentity(priKey);
            }
            if (sshConnect.getType() == 3) {
                String priKey = SshKeyUtil.getPriKeyFileName(sshConnect.getIdentity());
                jsch.addIdentity(priKey);
            }
            sshSession = jsch.getSession(sshConnect.getUsername(), sshConnect.getHost(), sshConnect.getPort());
            if (sshConnect.getType() == 2) {
                sshSession.setPassword(sshConnect.getPassword());
            }
            sshSession.setConfig("StrictHostKeyChecking", "no");
            sshSession.connect(5000);
        } catch (Exception e) {
            log.error("连通[{}]失败", sshConnect.getHost(), e);
            SystemErrorType.INTERNAL_SERVER_ERROR.throwError("连通失败");
        }
        return sshSession;

    }

    @Override
    public OsInfo testConnect(SshConnect sshConnect) {
        Session sshSession = getSshSession(sshConnect);
        return new OsCommand(sshSession).exec();
    }

    @Override
    public void sshCopyId(SshConnect sshConnect) {
        Session sshSession = getSshSession(sshConnect);
        SshSetting sshSetting = systemSettingService.getSettingItem(SshSetting.class);
        new SshCopyIdCommand(sshSession).exec(sshSetting.getPubKey());
    }

}
